package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.DeletionIsNotAllowed;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StuMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzRequestParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StuMapper  stuMapper;

    /**
     * 条件分页查询班级信息
     * */
    @Override
    public PageResult<Clazz> page(ClazzRequestParam clazzRequestParam) {
        //1、设置分页参数
        PageHelper.startPage(clazzRequestParam.getPage(), clazzRequestParam.getPageSize());

        //2、调用mapper层方法查询数据
        List<Clazz> clazzList = clazzMapper.list(clazzRequestParam);

        //3、封装成PageResult对象并返回
        Page<Clazz> result = (Page<Clazz>) clazzList;
        return new PageResult<>(result.getTotal(), result.getResult());
    }

    /**
     * 删除指定班级
     * */
    @Override
    public void deleteById(Integer id) {
        //统计该班级的学员人数
        Integer count = stuMapper.selectByClazzId(id);
        if (count > 0) {
            throw new DeletionIsNotAllowed("该班级有学员，不能删除");
        }

        //调用mapper层方法删除指定班级
        clazzMapper.deleteById(id);
    }

    /**
     * 添加班级
     * */
    @Override
    public void add(Clazz clazz) {
        //补全基础数据
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());

        //调用mapper层方法添加班级
        clazzMapper.add(clazz);
    }

    /**
     * 根据id查询班级信息
     * */
    @Override
    public Clazz selectById(Integer id) {
        return clazzMapper.selectById(id);
    }

    /**
     * 修改班级信息
     * */
    @Override
    public void update(Clazz clazz) {
        //补全基础数据
        clazz.setUpdateTime(LocalDateTime.now());

        //调用mapper层方法修改班级信息
        clazzMapper.update(clazz);
    }

    @Override
    public List<Clazz> selectAll() {
        return clazzMapper.selectAll();
    }
}
